﻿using IceDog.DNF.Program.Mvc5.EfContext;
using System.Linq;
using System.Net;
using System.Text;
using System.Web.Mvc;
using System.Web.Security;
using IceDog.DNF.Program.Mvc5.Models;
using IceDog.DNF.Program.Mvc5.Repository;
using PagedList;

namespace IceDog.DNF.Program.Mvc5.Controllers
{
    public class AccountController : Controller
    {
        private readonly AccountContext _db;
        private ISystemUserRepository _repository;

        public AccountController()
        {
            _db = new AccountContext();
            _repository = new SystemUserRepository();
        }
        // GET: Account
        [HttpGet]
        public ActionResult Index(string sortOrder, string searchString, int? pageNumber)
        {
            //设置默认值
            if (ViewBag.pageSize == null)
            {
                ViewBag.pageSize = 3;
            }
            if (ViewBag.pageNumber == null)
            {
                ViewBag.pageNumber = 1;
            }
            if (ViewBag.sortOrder == null)
            {
                ViewBag.sortOrder = "asc";
            }
            if (ViewBag.searchString == null)
            {
                ViewBag.searchString = "";
            }

            //判断参数是否有值，有值则覆盖
            if (!string.IsNullOrEmpty(sortOrder))
            {
                ViewBag.sortOrder = sortOrder == "asc" ? "desc" : "asc";
            }
            if (!string.IsNullOrEmpty(searchString))
            {
                ViewBag.searchString = searchString;
                pageNumber = 1;
            }
            if (pageNumber.HasValue)
            {
                ViewBag.pageNumber = pageNumber.Value;
            }

            //把ViewBag的值读取出来
            string vsortOrder = ViewBag.sortOrder;
            string vsearchString = ViewBag.searchString;
            int vpageNumber = ViewBag.pageNumber;
            int vpageSize = ViewBag.pageSize;

            //把读取的值进行使用
            var users = from user in _db.SystemUsers select user;
            if (!string.IsNullOrEmpty(vsortOrder))
            {
                if (vsortOrder.Equals("asc"))
                {
                    users = users.OrderBy(u => u.UserName.ToLower());
                }
                if (vsortOrder.Equals("desc"))
                {
                    users = users.OrderByDescending(u => u.UserName);
                }
            }
            if (!string.IsNullOrEmpty(vsearchString))
            {
                users = users.Where(u => u.UserName.Contains(vsearchString));
            }
            return View(users.ToPagedList(vpageNumber, vpageSize));
        }

        // GET: Account/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            SystemUser systemUser = _db.SystemUsers.Find(id);
            if (systemUser == null)
            {
                return HttpNotFound();
            }
            return View(systemUser);
        }

        // GET: Account/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            SystemUser systemUser = _db.SystemUsers.Find(id);
            if (systemUser == null)
            {
                return HttpNotFound();
            }
            return View(systemUser);
        }

        // POST: Account/Delete/5
        [HttpPost]
        public ActionResult Delete(int id)
        {
            SystemUser systemUser = _db.SystemUsers.Find(id);
            if (systemUser == null)
            {
                return HttpNotFound();
            }
            _repository.RemoveSystemUser(id);
            return RedirectToAction("Index");
        }
        // GET: Account/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            SystemUser systemUser = _db.SystemUsers.Find(id);
            if (systemUser == null)
            {
                return HttpNotFound();
            }
            return View(systemUser);
        }

        [HttpPost]
        public ActionResult Edit(SystemUser systemUser)
        {
            _repository.EditSystemUser(systemUser);
            return RedirectToAction("Index");
        }
        // GET: Account/Create
        public ActionResult Create()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Create(SystemUser systemUser)
        {
            _repository.AddSystemUser(systemUser);
            return RedirectToAction("Index");
        }

        // GET: Login
        [HttpGet]
        public ActionResult Login()
        {
            ViewBag.LoginState = "您还未登录，请登录";
            return View();
        }
        // POST: Login
        [HttpPost]
        public ActionResult Login(FormCollection form)
        {
            var account = form["account"];
            var password = form["password"];
            var user = _db.SystemUsers.FirstOrDefault(
              u => u.UserName.Equals(account) && u.Password.Equals(password));
            var greet = string.Empty;
            if (user != null)
            {
                greet = $"您好，{account}，欢迎回来";
                //FormsAuthentication.SetAuthCookie(user.UserName,true);//3000分钟有效期的cookie //remember me
                FormsAuthentication.SetAuthCookie(user.UserName, false);  //会话cookie
            }
            else
            {
                greet = $"账号密码错误";
            }
            return View();
        }
        // GET: Register
        [HttpGet]
        public ActionResult Register()
        {
            ViewBag.RegisterState = "欢迎注册！";
            return View();
        }

        // POST: Register
        [HttpPost]
        public ActionResult Register(FormCollection form)
        {
            var userName = form["account"];
            var password = form["password"];
            var password2 = form["password2"];
            if (password != password2)
            {
                ViewBag.RegisterState = "两次密码不一致！";
                return View();
            }
            var user = _repository.GetAllSystemUser().Where(u => u.UserName.Equals(userName)).ToList();
            if (user.Count == 0)
            {
                _repository.AddSystemUser(new SystemUser
                {
                    UserName = userName,
                    Password = password
                });
                ViewBag.RegisterState = "注册成功！";
            }
            else
            {
                ViewBag.RegisterState = "用户名已存在！";
            }
            return View();
        }

        #region query

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetAllSystemUser()
        {
            IQueryable<SystemUser> alluser1;
            IQueryable<SystemUser> alluser2;
            alluser1 = _db.SystemUsers;
            alluser2 = from user in _db.SystemUsers select user;
            return Json(new
            {
                alluser1 = alluser1.ToList(),
                alluser2 = alluser2.ToList()
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetSystemUserByUserName(string userName)
        {
            IQueryable<SystemUser> alluser1;
            IQueryable<SystemUser> alluser2;

            alluser1 = _db.SystemUsers
               .Where(user => user.UserName.Equals(userName));

            alluser2 = from user in _db.SystemUsers
                       where (user.UserName.Equals(userName))
                       select user;
            return Json(new
            {
                alluser1 = alluser1.ToList(),
                alluser2 = alluser2.ToList()
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sortField"></param>
        /// <param name="sortOrder"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult GetSystemUserBySpanDataAndSort(string sortField, string sortOrder
            , int pageIndex, int pageSize)
        {
            IQueryable<SystemUser> alluser1;
            IQueryable<SystemUser> alluser2;
            if (sortOrder.Equals("asc"))
            {
                alluser1 = _db.SystemUsers
                    .OrderBy(u => u.UserName)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);

                alluser2 = (from user in _db.SystemUsers
                            orderby user.UserName ascending
                            select user)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);
            }
            else
            {
                alluser1 = _db.SystemUsers
                    .OrderByDescending(u => u.UserName)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);

                alluser2 = (from user in _db.SystemUsers
                            orderby user.UserName descending
                            select user)
                    .Skip((pageIndex - 1) * pageSize)
                    .Take(pageSize);
            }
            return Json(new
            {
                alluser1 = alluser1.ToList(),
                alluser2 = alluser2.ToList()
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult GetAllSystemUserCount()
        {
            var count = _db.SystemUsers.Count();
            return Json(new
            {
                count = count
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }
        [HttpGet]
        public ActionResult GetMinAndMaxSystemUserId()
        {
            var min = _db.SystemUsers.Min(u => u.Id);
            var max = _db.SystemUsers.Max(u => u.Id);
            return Json(new
            {
                min = min,
                max = max
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult GeSystemUseRoles()
        {
            var userRoles = from ur in _db.SystemUserRoles
                            join u in _db.SystemUsers on ur.SystemUserId equals u.Id
                            select ur;
            return Json(new
            {
                userRoles = userRoles,
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region update
        /// <summary>
        /// 数据更新,分三步：找到对象--> 更新对象数据--> 保存更改
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="userName"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult UpdateSystemUserNameByUserId(int userId, string userName)
        {
            var user = _db.SystemUsers.FirstOrDefault(u => u.Id.Equals(userId));
            if (user != null)
            {
                user.UserName = userName;
            }
            _db.SaveChanges();
            return Json(new
            {
                result = "success",
                user,
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region delete
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult DeleteSystemUserByUserId(int userId)
        {
            var user = _db.SystemUsers.FirstOrDefault(u => u.Id.Equals(userId));
            if (user != null)
            {
                _db.SystemUsers.Remove(user);
                _db.SaveChanges();
            }

            return Json(new
            {
                result = "success",
                user,
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region add
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult AddSystemUser(string userName, string password)
        {
            var user = new SystemUser()
            {
                UserName = userName,
                Password = password,
                Email = "123456@qq.com",
            };
            _db.SystemUsers.Add(user);
            _db.SaveChanges();
            return Json(new
            {
                result = "success",
                user,
            }, "application/json", Encoding.UTF8, JsonRequestBehavior.AllowGet);
        }
        #endregion
    }
}